package org.example.MedicalCrowdsourcing.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.MedicalCrowdsourcing.model.bo.*;
import org.example.MedicalCrowdsourcing.model.entity.BlockchainProject;
import org.example.MedicalCrowdsourcing.model.entity.User;
import org.example.MedicalCrowdsourcing.repository.UserRepository;
import org.example.MedicalCrowdsourcing.service.BlockchainSyncService;
import org.example.MedicalCrowdsourcing.service.MedicalCrowdsourcingService;
import org.example.MedicalCrowdsourcing.service.UserService;
import org.fisco.bcos.sdk.transaction.model.dto.CallResponse;
import org.fisco.bcos.sdk.transaction.model.dto.TransactionResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/medical-crowdsourcing")
@CrossOrigin(origins = "http://localhost:8081", allowCredentials = "true")
@Slf4j
public class MedicalCrowdsourcingController {

    private static final String FIXED_USER_ADDRESS = "0x0add2420fbb95935ed17f6829f9979d1e4f57e83";

    @Autowired
    @Qualifier("MedicalCrowdsourcingService")
    private Map<String, MedicalCrowdsourcingService> serviceMap;
    
    @Autowired
    private BlockchainSyncService blockchainSyncService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private UserRepository userRepository;

    /**
     * Get service instance for the current user - now using fixed address
     * @return The service instance
     * @throws Exception If service for the fixed address doesn't exist
     */
    private MedicalCrowdsourcingService getService() throws Exception {
        MedicalCrowdsourcingService service = serviceMap.get(FIXED_USER_ADDRESS);
        if (service == null) {
            throw new Exception("Service not found for fixed user address: " + FIXED_USER_ADDRESS);
        }
        return service;
    }
    
    /**
     * 获取当前登录用户（如果未登录则返回null）
     */
    private User getCurrentUser() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated() || 
                    "anonymousUser".equals(authentication.getPrincipal())) {
                return null;
            }
            
            String username = authentication.getName();
            return userRepository.findByUsername(username).orElse(null);
        } catch (Exception e) {
            log.error("获取当前用户失败: {}", e.getMessage());
            return null;
        }
    }

    /**
     * Create a new medical crowdsourcing project
     */
    @PostMapping("/projects")
    public ResponseEntity<?> createProject(
            @Valid @RequestBody MedicalCrowdsourcingCreateProjectInputBO input) {
        try {
            MedicalCrowdsourcingService service = getService();
            TransactionResponse response = service.createProject(input);
            
            Map<String, Object> result = new HashMap<>();
            result.put("transactionHash", response.getTransactionReceipt().getTransactionHash());
            result.put("blockNumber", response.getTransactionReceipt().getBlockNumber());
            result.put("status", response.getTransactionReceipt().getStatus());
            result.put("output", response.getValues());
            
            // 获取项目ID (假设返回值中包含项目ID)
            BigInteger projectId = extractProjectIdFromResponse(response);
            
            if (projectId != null) {
                // 同步到本地数据库
                User currentUser = getCurrentUser();
                String username = currentUser != null ? currentUser.getUsername() : null;
                
                blockchainSyncService.saveProjectToLocal(
                        projectId,
                        input.get_title(),
                        input.get_description(),
                        0, // 新建状态
                        null, // 没有dataHash字段，设为null
                        response.getTransactionReceipt().getTransactionHash(),
                        username
                );
                
                // 保存交易记录
                blockchainSyncService.syncTransactionAfterBlockchainOperation(
                        response,
                        projectId,
                        "创建项目: " + input.get_title(),
                        username
                );
                
                result.put("projectId", projectId);
                log.info("项目数据已同步到本地数据库, 项目ID: {}", projectId);
            }
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("Error creating project", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error creating project: " + e.getMessage());
        }
    }
    
    /**
     * 从响应中提取项目ID
     */
    private BigInteger extractProjectIdFromResponse(TransactionResponse response) {
        try {
            // 尝试从响应值中解析项目ID
            // 注意：这里的实现需要根据合约返回值格式调整
            String values = response.getValues();
            if (values != null && !values.isEmpty()) {
                // 假设返回格式是 "[\"1\"]" 格式的字符串
                values = values.replaceAll("[\\[\\]\"\\s]", "");
                return new BigInteger(values);
            }
            return null;
        } catch (Exception e) {
            log.error("解析项目ID失败: {}", e.getMessage());
            return null;
        }
    }

    /**
     * Get all project IDs
     */
    @GetMapping("/projects")
    public ResponseEntity<?> getAllProjectIds() {
        try {
            MedicalCrowdsourcingService service = getService();
            MedicalCrowdsourcingGetAllProjectIdsInputBO input = new MedicalCrowdsourcingGetAllProjectIdsInputBO();
            CallResponse response = service.getAllProjectIds(input);
            
            return ResponseEntity.ok(response.getValues());
        } catch (Exception e) {
            log.error("Error getting all project IDs", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error getting all project IDs: " + e.getMessage());
        }
    }

    /**
     * 列出所有项目信息 - 通过遍历方式获取
     * 替代getAllProjectIds方法
     */
    @GetMapping("/projects/list")
    public ResponseEntity<?> listAllProjects() {
        try {
            // 获取服务实例
            MedicalCrowdsourcingService service = getService();
            
            // 创建结果列表
            List<Map<String, Object>> projects = new ArrayList<>();
            
            // 获取项目总数 - 直接使用服务方法
            CallResponse countResponse = service.projectCount();
            log.info("项目总数响应: " + countResponse.getValues());
            
            // 解析项目总数
            int count = 0;
//            if (countResponse.getValues() instanceof List) {
//                List<?> countList = (List<?>) countResponse.getValues();
//                if (!countList.isEmpty() && countList.get(0) != null) {
//                    count = Integer.parseInt(countList.get(0).toString());
//                    log.info("解析出的项目总数: " + count);
//                }
//            }
            String valuesStr = countResponse.getValues();
// 去除方括号并分割
            String[] parts = valuesStr.replaceAll("[\\[\\]\"]", "").split(",");
            if (parts.length > 0 && !parts[0].isEmpty()) {
                count = Integer.parseInt(parts[0]);
                log.info("解析出的项目总数: " + count);
            }
            
            // 遍历获取所有项目
            for (int i = 1; i <= Math.max(count, 2); i++) { // 至少尝试获取前两个项目
                try {
                    // 创建项目对象
                    Map<String, Object> project = new HashMap<>();
                    project.put("id", i);
                    
                    // 获取项目基本信息1
                    MedicalCrowdsourcingGetProjectBasic1InputBO input1 = new MedicalCrowdsourcingGetProjectBasic1InputBO();
                    input1.set_projectId(BigInteger.valueOf(i));
                    CallResponse response1 = service.getProjectBasic1(input1);
                    
                    if (response1.getValues() != null) {
                        project.put("basic1", response1.getValues());
                        
                        // 获取项目基本信息2
                        try {
                            MedicalCrowdsourcingGetProjectBasic2InputBO input2 = new MedicalCrowdsourcingGetProjectBasic2InputBO();
                            input2.set_projectId(BigInteger.valueOf(i));
                            CallResponse response2 = service.getProjectBasic2(input2);
                            
                            if (response2.getValues() != null) {
                                project.put("basic2", response2.getValues());
                            } else {
                                project.put("basic2", Collections.emptyList());
                                log.warn("项目" + i + "的basic2为null，使用空列表代替");
                            }
                        } catch (Exception e) {
                            project.put("basic2", Collections.emptyList());
                            log.error("获取项目" + i + "的basic2失败: " + e.getMessage());
                        }
                        
                        // 添加项目到列表
                        projects.add(project);
                        log.info("成功添加项目" + i + "到列表");
                    }
                } catch (Exception e) {
                    log.error("获取项目" + i + "失败: " + e.getMessage());
                }
            }
            
            log.info("最终项目列表大小: " + projects.size());
            return ResponseEntity.ok(projects);
        } catch (Exception e) {
            log.error("获取项目列表失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error listing all projects: " + e.getMessage());
        }
    }

    /**
     * Get project basic information (part 1)
     */
    @GetMapping("/projects/{projectId}/basic1")
    public ResponseEntity<?> getProjectBasic1(
            @PathVariable String projectId) {
        try {
            MedicalCrowdsourcingService service = getService();
            MedicalCrowdsourcingGetProjectBasic1InputBO input = new MedicalCrowdsourcingGetProjectBasic1InputBO();
            input.set_projectId(new BigInteger(projectId));
            CallResponse response = service.getProjectBasic1(input);
            
            return ResponseEntity.ok(response.getValues());
        } catch (Exception e) {
            log.error("Error getting project basic info 1", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error getting project basic info 1: " + e.getMessage());
        }
    }

    /**
     * Get project basic information (part 2)
     */
    @GetMapping("/projects/{projectId}/basic2")
    public ResponseEntity<?> getProjectBasic2(
            @PathVariable String projectId) {
        try {
            MedicalCrowdsourcingService service = getService();
            MedicalCrowdsourcingGetProjectBasic2InputBO input = new MedicalCrowdsourcingGetProjectBasic2InputBO();
            input.set_projectId(new BigInteger(projectId));
            CallResponse response = service.getProjectBasic2(input);
            
            return ResponseEntity.ok(response.getValues());
        } catch (Exception e) {
            log.error("Error getting project basic info 2", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error getting project basic info 2: " + e.getMessage());
        }
    }

    /**
     * Update an existing project
     */
    @PostMapping("/projects/{projectId}/update")
    public ResponseEntity<?> updateProject(
            @PathVariable String projectId,
            @Valid @RequestBody MedicalCrowdsourcingUpdateProjectInputBO input) {
        try {
            input.set_projectId(new BigInteger(projectId)); // Ensure projectId from path is used
            MedicalCrowdsourcingService service = getService();
            TransactionResponse response = service.updateProject(input);
            
            Map<String, Object> result = new HashMap<>();
            result.put("transactionHash", response.getTransactionReceipt().getTransactionHash());
            result.put("blockNumber", response.getTransactionReceipt().getBlockNumber());
            result.put("status", response.getTransactionReceipt().getStatus());
            result.put("output", response.getValues());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("Error updating project", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error updating project: " + e.getMessage());
        }
    }

    /**
     * Complete a project
     */
    @PostMapping("/projects/{projectId}/complete")
    public ResponseEntity<?> completeProject(
            @PathVariable String projectId,
            @Valid @RequestBody MedicalCrowdsourcingCompleteProjectInputBO input) {
        try {
            input.set_projectId(new BigInteger(projectId)); // Ensure projectId from path is used
            MedicalCrowdsourcingService service = getService();
            TransactionResponse response = service.completeProject(input);
            
            Map<String, Object> result = new HashMap<>();
            result.put("transactionHash", response.getTransactionReceipt().getTransactionHash());
            result.put("blockNumber", response.getTransactionReceipt().getBlockNumber());
            result.put("status", response.getTransactionReceipt().getStatus());
            result.put("output", response.getValues());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("Error completing project", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error completing project: " + e.getMessage());
        }
    }

    /**
     * Delete a project
     */
    @DeleteMapping("/projects/{projectId}")
    public ResponseEntity<?> deleteProject(
            @PathVariable String projectId) {
        try {
            MedicalCrowdsourcingDeleteProjectInputBO input = new MedicalCrowdsourcingDeleteProjectInputBO();
            input.set_projectId(new BigInteger(projectId));
            MedicalCrowdsourcingService service = getService();
            TransactionResponse response = service.deleteProject(input);
            
            Map<String, Object> result = new HashMap<>();
            result.put("transactionHash", response.getTransactionReceipt().getTransactionHash());
            result.put("blockNumber", response.getTransactionReceipt().getBlockNumber());
            result.put("status", response.getTransactionReceipt().getStatus());
            result.put("output", response.getValues());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("Error deleting project", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error deleting project: " + e.getMessage());
        }
    }

    /**
     * Get project timestamps
     */
    @GetMapping("/projects/{projectId}/times")
    public ResponseEntity<?> getProjectTimes(
            @PathVariable String projectId) {
        try {
            MedicalCrowdsourcingGetProjectTimesInputBO input = new MedicalCrowdsourcingGetProjectTimesInputBO();
            input.set_projectId(new BigInteger(projectId));
            MedicalCrowdsourcingService service = getService();
            CallResponse response = service.getProjectTimes(input);
            
            return ResponseEntity.ok(response.getValues());
        } catch (Exception e) {
            log.error("Error getting project times", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error getting project times: " + e.getMessage());
        }
    }

    /**
     * Verify project hash
     */
    @PostMapping("/projects/{projectId}/verify-hash")
    public ResponseEntity<?> verifyProjectHash(
            @PathVariable String projectId,
            @Valid @RequestBody MedicalCrowdsourcingVerifyProjectHashInputBO input) {
        try {
            input.set_projectId(new BigInteger(projectId)); // Ensure projectId from path is used
            MedicalCrowdsourcingService service = getService();
            CallResponse response = service.verifyProjectHash(input);
            
            return ResponseEntity.ok(response.getValues());
        } catch (Exception e) {
            log.error("Error verifying project hash", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error verifying project hash: " + e.getMessage());
        }
    }

    /**
     * Get project history IDs
     */
    @GetMapping("/projects/{projectId}/history-ids")
    public ResponseEntity<?> getProjectHistoryIds(
            @PathVariable String projectId) {
        try {
            MedicalCrowdsourcingGetProjectHistoryIdsInputBO input = new MedicalCrowdsourcingGetProjectHistoryIdsInputBO();
            input.set_projectId(new BigInteger(projectId));
            MedicalCrowdsourcingService service = getService();
            CallResponse response = service.getProjectHistoryIds(input);
            
            return ResponseEntity.ok(response.getValues());
        } catch (Exception e) {
            log.error("Error getting project history IDs", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error getting project history IDs: " + e.getMessage());
        }
    }

    /**
     * 列出所有历史记录 - 通过遍历方式获取
     * 替代getProjectHistoryIds方法
     */
    @GetMapping("/history/list")
    public ResponseEntity<?> listAllHistories() {
        try {
            MedicalCrowdsourcingService service = getService();
            
            // 先获取历史记录总数
            CallResponse countResponse = service.historyCount();
            log.info("历史记录总数响应: " + countResponse.getValues());
            
            // 创建结果列表
            List<Map<String, Object>> histories = new ArrayList<>();
            
            // 使用与projectCount相同的方式解析历史记录总数
            int count = 0;
            String valuesStr = countResponse.getValues();
            
            // 去除方括号并分割
            String[] parts = valuesStr.replaceAll("[\\[\\]\"]", "").split(",");
            if (parts.length > 0 && !parts[0].isEmpty()) {
                count = Integer.parseInt(parts[0]);
                log.info("解析出的历史记录总数: " + count);
            }
            
            // 如果有历史记录，尝试获取
            if (count > 0) {
                // 遍历所有历史记录ID
                for(int i = 1; i <= count; i++) {
                    try {
                        log.info("尝试获取历史记录ID: " + i);
                        MedicalCrowdsourcingGetProjectHistoryDetailsInputBO input = new MedicalCrowdsourcingGetProjectHistoryDetailsInputBO();
                        input.set_historyId(BigInteger.valueOf(i));
                        
                        CallResponse response = service.getProjectHistoryDetails(input);
                        if (response != null && response.getValues() != null) {
                            log.info("历史记录" + i + "响应: " + response.getValues());
                            
                            Map<String, Object> history = new HashMap<>();
                            history.put("id", i);
                            history.put("details", response.getValues());
                            histories.add(history);
                            log.info("成功添加历史记录" + i + "到结果列表");
                        } else {
                            log.warn("历史记录" + i + "响应为空");
                        }
                    } catch (Exception e) {
                        // 如果历史记录不存在，则跳过
                        log.error("获取历史记录" + i + "失败: " + e.getMessage());
                    }
                }
            } else {
                log.warn("没有找到历史记录，count=" + count);
            }
            
            // 输出结果
            log.info("最终历史记录列表大小: " + histories.size());
            if (histories.isEmpty()) {
                log.warn("历史记录列表为空！");
            } else {
                log.info("历史记录列表内容: " + histories);
            }
            
            return ResponseEntity.ok(histories);
        } catch (Exception e) {
            log.error("获取历史记录列表失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error listing all histories: " + e.getMessage());
        }
    }
    
    /**
     * 获取特定项目的所有历史记录 - 替代方案
     */
    @GetMapping("/projects/{projectId}/history-list")
    public ResponseEntity<?> listProjectHistories(
            @PathVariable String projectId) {
        try {
            MedicalCrowdsourcingService service = getService();
            
            // 先获取历史记录总数
            CallResponse countResponse = service.historyCount();
            log.info("历史记录总数响应: " + countResponse.getValues());
            
            BigInteger projectIdBigInt = new BigInteger(projectId);
            List<Map<String, Object>> histories = new ArrayList<>();
            
            // 使用与projectCount相同的方式解析历史记录总数
            int count = 0;
            String valuesStr = countResponse.getValues();
            
            // 去除方括号并分割
            String[] parts = valuesStr.replaceAll("[\\[\\]\"]", "").split(",");
            if (parts.length > 0 && !parts[0].isEmpty()) {
                count = Integer.parseInt(parts[0]);
                log.info("解析出的历史记录总数: " + count + ", 查找项目ID: " + projectId);
            }
            
            // 遍历所有历史记录，找出与项目相关的
            for(int i = 1; i <= count; i++) {
                try {
                    log.info("尝试获取历史记录ID: " + i);
                    MedicalCrowdsourcingGetProjectHistoryDetailsInputBO input = new MedicalCrowdsourcingGetProjectHistoryDetailsInputBO();
                    input.set_historyId(BigInteger.valueOf(i));
                    
                    CallResponse response = service.getProjectHistoryDetails(input);
                    if (response != null && response.getValues() != null) {
                        log.info("历史记录" + i + "响应: " + response.getValues());
                        
                        // 检查历史记录是否与指定项目相关
                        Object values = response.getValues();
                        if (values instanceof List && !((List<?>)values).isEmpty()) {
                            // 假设第一个元素是项目ID，需要根据实际返回调整
                            try {
                                List<?> valuesList = (List<?>) values;
                                if (valuesList.get(0) != null) {
                                    BigInteger historyProjectId = new BigInteger(valuesList.get(0).toString());
                                    if (historyProjectId.equals(projectIdBigInt)) {
                                        Map<String, Object> history = new HashMap<>();
                                        history.put("id", i);
                                        history.put("details", values);
                                        histories.add(history);
                                        log.info("历史记录" + i + "匹配项目ID " + projectId + "，已添加");
                                    } else {
                                        log.info("历史记录" + i + "不匹配项目ID " + projectId + "，跳过");
                                    }
                                }
                            } catch (Exception e) {
                                log.debug("无法从历史记录解析项目ID: " + e.getMessage());
                            }
                        }
                    } else {
                        log.warn("历史记录" + i + "响应为空");
                    }
                } catch (Exception e) {
                    // 如果历史记录不存在，则跳过
                    log.debug("历史记录" + i + "可能不存在: " + e.getMessage());
                }
            }
            
            log.info("最终找到的项目" + projectId + "相关历史记录数: " + histories.size());
            if (histories.isEmpty()) {
                log.warn("项目" + projectId + "的历史记录列表为空！");
            }
            
            return ResponseEntity.ok(histories);
        } catch (Exception e) {
            log.error("获取项目历史记录列表失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error listing project histories: " + e.getMessage());
        }
    }
    
    /**
     * Get project history details
     */
    @GetMapping("/projects/history/{historyId}")
    public ResponseEntity<?> getProjectHistoryDetails(
            @PathVariable String historyId) {
        try {
            MedicalCrowdsourcingGetProjectHistoryDetailsInputBO input = new MedicalCrowdsourcingGetProjectHistoryDetailsInputBO();
            input.set_historyId(new BigInteger(historyId));
            MedicalCrowdsourcingService service = getService();
            CallResponse response = service.getProjectHistoryDetails(input);
            
            return ResponseEntity.ok(response.getValues());
        } catch (Exception e) {
            log.error("Error getting project history details", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error getting project history details: " + e.getMessage());
        }
    }

    /**
     * Get project transactions
     */
    @GetMapping("/projects/{projectId}/transactions")
    public ResponseEntity<?> getProjectTransactions(
            @PathVariable String projectId) {
        try {
            MedicalCrowdsourcingGetProjectTransactionsInputBO input = new MedicalCrowdsourcingGetProjectTransactionsInputBO();
            input.set_projectId(new BigInteger(projectId));
            MedicalCrowdsourcingService service = getService();
            CallResponse response = service.getProjectTransactions(input);
            
            return ResponseEntity.ok(response.getValues());
        } catch (Exception e) {
            log.error("Error getting project transactions", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error getting project transactions: " + e.getMessage());
        }
    }

    /**
     * 列出所有交易记录 - 通过遍历方式
     */
    @GetMapping("/transactions/list")
    public ResponseEntity<?> listAllTransactions() {
        try {
            MedicalCrowdsourcingService service = getService();
            
            // 先获取项目总数
            CallResponse projectCountResponse = service.projectCount();
            log.info("项目总数响应: " + projectCountResponse.getValues());
            
            List<Map<String, Object>> allTransactions = new ArrayList<>();
            
            // 解析项目总数
            int projectCount = 0;
            try {
                Object countValues = projectCountResponse.getValues();
                if (countValues instanceof List) {
                    List<?> countList = (List<?>) countValues;
                    if (!countList.isEmpty() && countList.get(0) != null) {
                        projectCount = Integer.parseInt(countList.get(0).toString());
                    }
                }
            } catch (Exception e) {
                log.error("解析项目总数出错", e);
            }
            
            log.info("解析后的项目总数: " + projectCount);
            
            // 遍历所有项目，获取每个项目的交易
            for(int i = 1; i <= projectCount; i++) {
                try {
                    log.info("获取项目" + i + "的交易列表");
                    
                    // 尝试获取项目的交易列表
                    MedicalCrowdsourcingGetProjectTransactionsInputBO input = new MedicalCrowdsourcingGetProjectTransactionsInputBO();
                    input.set_projectId(BigInteger.valueOf(i));
                    
                    CallResponse response = service.getProjectTransactions(input);
                    log.info("项目" + i + "的交易列表响应: " + response.getValues());
                    
                    Object txObj = response.getValues();
                    
                    // 处理交易列表
                    if (txObj instanceof List) {
                        List<?> txList = (List<?>) txObj;
                        log.info("项目" + i + "的交易数量: " + txList.size());
                        
                        for (Object txHash : txList) {
                            if (txHash != null) {
                                try {
                                    log.info("获取交易详情: " + txHash);
                                    
                                    // 获取每个交易的详细信息
                                    MedicalCrowdsourcingGetTransactionDetailsInputBO txInput = new MedicalCrowdsourcingGetTransactionDetailsInputBO();
                                    txInput.set_txHash(txHash.toString().getBytes());
                                    
                                    CallResponse txResponse = service.getTransactionDetails(txInput);
                                    log.info("交易详情响应: " + txResponse.getValues());
                                    
                                    Map<String, Object> transaction = new HashMap<>();
                                    transaction.put("hash", txHash.toString());
                                    transaction.put("projectId", i);
                                    transaction.put("details", txResponse.getValues());
                                    allTransactions.add(transaction);
                                    
                                    log.info("成功添加交易到结果列表");
                                } catch (Exception e) {
                                    log.error("获取交易详情失败: " + e.getMessage(), e);
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    // 如果项目不存在，则跳过
                    log.error("获取项目" + i + "的交易列表失败: " + e.getMessage(), e);
                }
            }
            
            log.info("最终交易列表大小: " + allTransactions.size());
            return ResponseEntity.ok(allTransactions);
        } catch (Exception e) {
            log.error("获取交易列表失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error listing all transactions: " + e.getMessage());
        }
    }

    /**
     * Get transaction details
     */
    @GetMapping("/transactions/{transactionId}")
    public ResponseEntity<?> getTransactionDetails(
            @PathVariable String transactionId) {
        try {
            MedicalCrowdsourcingGetTransactionDetailsInputBO input = new MedicalCrowdsourcingGetTransactionDetailsInputBO();
            input.set_txHash(transactionId.getBytes());
            MedicalCrowdsourcingService service = getService();
            CallResponse response = service.getTransactionDetails(input);
            
            return ResponseEntity.ok(response.getValues());
        } catch (Exception e) {
            log.error("Error getting transaction details", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error getting transaction details: " + e.getMessage());
        }
    }

    /**
     * Get total project count
     */
    @GetMapping("/projects/count")
    public ResponseEntity<?> getProjectCount() {
        try {
            MedicalCrowdsourcingService service = getService();
            CallResponse response = service.projectCount();
            
            return ResponseEntity.ok(response.getValues());
        } catch (Exception e) {
            log.error("Error getting project count", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error getting project count: " + e.getMessage());
        }
    }

    /**
     * Get total history count
     */
    @GetMapping("/history/count")
    public ResponseEntity<?> getHistoryCount() {
        try {
            MedicalCrowdsourcingService service = getService();
            CallResponse response = service.historyCount();
            
            return ResponseEntity.ok(response.getValues());
        } catch (Exception e) {
            log.error("Error getting history count", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error getting history count: " + e.getMessage());
        }
    }

    /**
     * Get contract owner
     */
    @GetMapping("/owner")
    public ResponseEntity<?> getOwner() {
        try {
            MedicalCrowdsourcingService service = getService();
            CallResponse response = service.owner();
            
            return ResponseEntity.ok(response.getValues());
        } catch (Exception e) {
            log.error("Error getting owner", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error getting owner: " + e.getMessage());
        }
    }

    /**
     * 专门测试获取项目ID=2的所有信息
     */
    @GetMapping("/projects/test-project2")
    public ResponseEntity<?> testProject2() {
        try {
            MedicalCrowdsourcingService service = getService();
            Map<String, Object> result = new HashMap<>();
            
            // 尝试获取项目ID=2的基本信息1
            try {
                MedicalCrowdsourcingGetProjectBasic1InputBO input1 = new MedicalCrowdsourcingGetProjectBasic1InputBO();
                input1.set_projectId(BigInteger.valueOf(2));
                CallResponse response1 = service.getProjectBasic1(input1);
                
                log.info("TEST - 项目ID=2基本信息1响应: " + response1.getValues());
                result.put("basic1_success", true);
                result.put("basic1", response1.getValues());
            } catch (Exception e) {
                log.error("TEST - 获取项目ID=2的基本信息1失败", e);
                result.put("basic1_success", false);
                result.put("basic1_error", e.getMessage());
            }
            
            // 尝试获取项目ID=2的基本信息2
            try {
                MedicalCrowdsourcingGetProjectBasic2InputBO input2 = new MedicalCrowdsourcingGetProjectBasic2InputBO();
                input2.set_projectId(BigInteger.valueOf(2));
                CallResponse response2 = service.getProjectBasic2(input2);
                
                log.info("TEST - 项目ID=2基本信息2响应: " + response2.getValues());
                result.put("basic2_success", true);
                result.put("basic2", response2.getValues());
            } catch (Exception e) {
                log.error("TEST - 获取项目ID=2的基本信息2失败", e);
                result.put("basic2_success", false);
                result.put("basic2_error", e.getMessage());
            }
            
            // 构建完整项目信息，即使部分数据获取失败
            Map<String, Object> project = new HashMap<>();
            project.put("id", 2);
            project.put("basic1", result.get("basic1"));
            project.put("basic2", result.get("basic2"));
            result.put("project", project);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("测试项目ID=2失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("测试项目ID=2失败: " + e.getMessage());
        }
    }
    
    /**
     * 手动构建项目列表（不依赖自动遍历），用于测试
     */
    @GetMapping("/projects/manual-list")
    public ResponseEntity<?> manualListProjects() {
        try {
            MedicalCrowdsourcingService service = getService();
            List<Map<String, Object>> projects = new ArrayList<>();
            
            // 手动获取项目ID=1
            try {
                Map<String, Object> project1 = new HashMap<>();
                project1.put("id", 1);
                
                MedicalCrowdsourcingGetProjectBasic1InputBO input1 = new MedicalCrowdsourcingGetProjectBasic1InputBO();
                input1.set_projectId(BigInteger.valueOf(1));
                CallResponse response1 = service.getProjectBasic1(input1);
                project1.put("basic1", response1.getValues());
                
                MedicalCrowdsourcingGetProjectBasic2InputBO input2 = new MedicalCrowdsourcingGetProjectBasic2InputBO();
                input2.set_projectId(BigInteger.valueOf(1));
                CallResponse response2 = service.getProjectBasic2(input2);
                project1.put("basic2", response2.getValues());
                
                projects.add(project1);
                log.info("手动添加项目ID=1成功");
            } catch (Exception e) {
                log.error("手动获取项目ID=1失败", e);
            }
            
            // 手动获取项目ID=2
            try {
                Map<String, Object> project2 = new HashMap<>();
                project2.put("id", 2);
                
                MedicalCrowdsourcingGetProjectBasic1InputBO input1 = new MedicalCrowdsourcingGetProjectBasic1InputBO();
                input1.set_projectId(BigInteger.valueOf(2));
                CallResponse response1 = service.getProjectBasic1(input1);
                project2.put("basic1", response1.getValues());
                
                try {
                    MedicalCrowdsourcingGetProjectBasic2InputBO input2 = new MedicalCrowdsourcingGetProjectBasic2InputBO();
                    input2.set_projectId(BigInteger.valueOf(2));
                    CallResponse response2 = service.getProjectBasic2(input2);
                    project2.put("basic2", response2.getValues());
                    log.info("项目ID=2的basic2响应: " + response2.getValues());
                } catch (Exception e) {
                    log.error("获取项目ID=2的basic2失败，使用空数组代替", e);
                    // 如果获取basic2失败，使用空数组代替
                    project2.put("basic2", Collections.emptyList());
                }
                
                projects.add(project2);
                log.info("手动添加项目ID=2成功");
            } catch (Exception e) {
                log.error("手动获取项目ID=2失败", e);
            }
            
            return ResponseEntity.ok(projects);
        } catch (Exception e) {
            log.error("手动获取项目列表失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("手动获取项目列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取项目统计信息
     * 包括项目总数、各状态项目分布、历史记录统计等
     */
    @GetMapping("/statistics/projects")
    public ResponseEntity<?> getProjectStatistics() {
        try {
            MedicalCrowdsourcingService service = getService();
            Map<String, Object> statistics = new HashMap<>();
            
            // 获取项目总数
            try {
                CallResponse countResponse = service.projectCount();
                String valuesStr = countResponse.getValues();
                String[] parts = valuesStr.replaceAll("[\\[\\]\"]", "").split(",");
                if (parts.length > 0 && !parts[0].isEmpty()) {
                    int count = Integer.parseInt(parts[0]);
                    statistics.put("totalProjects", count);
                    log.info("统计 - 项目总数: " + count);
                }
            } catch (Exception e) {
                log.error("统计 - 获取项目总数失败", e);
                statistics.put("totalProjects", 0);
            }
            
            // 获取项目状态分布
            Map<String, Integer> statusDistribution = new HashMap<>();
            statusDistribution.put("ACTIVE", 0);
            statusDistribution.put("COMPLETED", 0);
            statusDistribution.put("DELETED", 0);
            
            // 获取历史记录总数
            try {
                CallResponse historyCountResponse = service.historyCount();
                String valuesStr = historyCountResponse.getValues();
                String[] parts = valuesStr.replaceAll("[\\[\\]\"]", "").split(",");
                if (parts.length > 0 && !parts[0].isEmpty()) {
                    int count = Integer.parseInt(parts[0]);
                    statistics.put("totalHistoryRecords", count);
                    log.info("统计 - 历史记录总数: " + count);
                }
            } catch (Exception e) {
                log.error("统计 - 获取历史记录总数失败", e);
                statistics.put("totalHistoryRecords", 0);
            }
            
            // 如果有项目，遍历统计状态
            int totalProjects = (int) statistics.getOrDefault("totalProjects", 0);
            if (totalProjects > 0) {
                for (int i = 1; i <= totalProjects; i++) {
                    try {
                        MedicalCrowdsourcingGetProjectBasic2InputBO input = new MedicalCrowdsourcingGetProjectBasic2InputBO();
                        input.set_projectId(BigInteger.valueOf(i));
                        CallResponse response = service.getProjectBasic2(input);
                        
                        if (response.getValues() != null) {
                            // 尝试解析出状态
                            String statusStr = response.getValues().toString();
                            if (statusStr.contains("true") && statusStr.contains("false")) {
                                if (statusStr.contains("true,false")) {
                                    // 已完成
                                    statusDistribution.put("COMPLETED", statusDistribution.get("COMPLETED") + 1);
                                } else if (statusStr.contains("false,true")) {
                                    // 已删除
                                    statusDistribution.put("DELETED", statusDistribution.get("DELETED") + 1);
                                } else {
                                    // 活跃
                                    statusDistribution.put("ACTIVE", statusDistribution.get("ACTIVE") + 1);
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error("统计 - 获取项目" + i + "状态失败", e);
                    }
                }
            }
            statistics.put("statusDistribution", statusDistribution);
            
            // 获取历史记录类型分布
            Map<String, Integer> historyTypeDistribution = new HashMap<>();
            historyTypeDistribution.put("CREATE", 0);
            historyTypeDistribution.put("UPDATE", 0);
            historyTypeDistribution.put("COMPLETE", 0);
            historyTypeDistribution.put("DELETE", 0);
            
            int totalHistory = (int) statistics.getOrDefault("totalHistoryRecords", 0);
            if (totalHistory > 0) {
                for (int i = 1; i <= totalHistory; i++) {
                    try {
                        MedicalCrowdsourcingGetProjectHistoryDetailsInputBO input = new MedicalCrowdsourcingGetProjectHistoryDetailsInputBO();
                        input.set_historyId(BigInteger.valueOf(i));
                        CallResponse response = service.getProjectHistoryDetails(input);
                        
                        if (response.getValues() != null) {
                            String valuesStr = response.getValues().toString();
                            if (valuesStr.contains(",0,")) {
                                historyTypeDistribution.put("CREATE", historyTypeDistribution.get("CREATE") + 1);
                            } else if (valuesStr.contains(",1,")) {
                                historyTypeDistribution.put("UPDATE", historyTypeDistribution.get("UPDATE") + 1);
                            } else if (valuesStr.contains(",2,")) {
                                historyTypeDistribution.put("COMPLETE", historyTypeDistribution.get("COMPLETE") + 1);
                            } else if (valuesStr.contains(",3,")) {
                                historyTypeDistribution.put("DELETE", historyTypeDistribution.get("DELETE") + 1);
                            }
                        }
                    } catch (Exception e) {
                        log.error("统计 - 获取历史记录" + i + "类型失败", e);
                    }
                }
            }
            statistics.put("historyTypeDistribution", historyTypeDistribution);
            
            // 获取最近10条历史记录
            List<Map<String, Object>> recentHistory = new ArrayList<>();
            if (totalHistory > 0) {
                int start = Math.max(1, totalHistory - 9); // 最多10条
                for (int i = totalHistory; i >= start; i--) {
                    try {
                        MedicalCrowdsourcingGetProjectHistoryDetailsInputBO input = new MedicalCrowdsourcingGetProjectHistoryDetailsInputBO();
                        input.set_historyId(BigInteger.valueOf(i));
                        CallResponse response = service.getProjectHistoryDetails(input);
                        
                        if (response.getValues() != null) {
                            Map<String, Object> history = new HashMap<>();
                            history.put("id", i);
                            history.put("details", response.getValues());
                            recentHistory.add(history);
                        }
                    } catch (Exception e) {
                        log.error("统计 - 获取历史记录" + i + "详情失败", e);
                    }
                }
            }
            statistics.put("recentHistory", recentHistory);
            
            return ResponseEntity.ok(statistics);
        } catch (Exception e) {
            log.error("获取项目统计信息失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error getting project statistics: " + e.getMessage());
        }
    }

    /**
     * Delete a project using POST method
     */
    @PostMapping("/projects/{projectId}/delete")
    public ResponseEntity<?> deleteProjectPost(
            @PathVariable String projectId,
            @Valid @RequestBody MedicalCrowdsourcingDeleteProjectInputBO input) {
        try {
            // 使用路径参数确保项目ID正确
            input.set_projectId(new BigInteger(projectId));
            
            // 处理_reason为空但_deleteReason不为空的情况
            if (input.get_reason() == null && input.get_deleteReason() != null) {
                input.set_reason(input.get_deleteReason());
            }
            
            MedicalCrowdsourcingService service = getService();
            TransactionResponse response = service.deleteProject(input);
            
            Map<String, Object> result = new HashMap<>();
            result.put("transactionHash", response.getTransactionReceipt().getTransactionHash());
            result.put("blockNumber", response.getTransactionReceipt().getBlockNumber());
            result.put("status", response.getTransactionReceipt().getStatus());
            result.put("output", response.getValues());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("Error deleting project", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error deleting project: " + e.getMessage());
        }
    }

    /**
     * 创建测试历史记录 - 用于调试
     */
    @PostMapping("/test/create-history")
    public ResponseEntity<?> createTestHistory() {
        try {
            MedicalCrowdsourcingService service = getService();
            
            // 1. 先创建一个新项目
            MedicalCrowdsourcingCreateProjectInputBO createInput = new MedicalCrowdsourcingCreateProjectInputBO();
            createInput.set_title("测试历史记录项目");
            createInput.set_description("这是一个用于测试历史记录的项目");
            createInput.set_researcherInfo("测试研究者");
            
            TransactionResponse createResponse = service.createProject(createInput);
            log.info("创建测试项目响应: " + createResponse.getValues());
            
            // 2. 获取项目总数，确定新项目ID
            CallResponse countResponse = service.projectCount();
            String countStr = countResponse.getValues();
            String[] parts = countStr.replaceAll("[\\[\\]\"]", "").split(",");
            int projectCount = Integer.parseInt(parts[0]);
            log.info("当前项目总数: " + projectCount);
            
            BigInteger newProjectId = BigInteger.valueOf(projectCount);
            
            // 3. 更新该项目，生成UPDATE历史记录
            MedicalCrowdsourcingUpdateProjectInputBO updateInput = new MedicalCrowdsourcingUpdateProjectInputBO();
            updateInput.set_projectId(newProjectId);
            updateInput.set_title("更新的测试历史记录项目");
            updateInput.set_description("这是一个已更新的测试项目");
            updateInput.set_researcherInfo("更新的测试研究者");
            updateInput.set_updateReason("测试生成历史记录");
            
            TransactionResponse updateResponse = service.updateProject(updateInput);
            log.info("更新测试项目响应: " + updateResponse.getValues());
            
            // 4. 获取历史记录总数
            CallResponse historyCountResponse = service.historyCount();
            String historyCountStr = historyCountResponse.getValues();
            parts = historyCountStr.replaceAll("[\\[\\]\"]", "").split(",");
            int historyCount = Integer.parseInt(parts[0]);
            log.info("当前历史记录总数: " + historyCount);
            
            // 返回测试结果
            Map<String, Object> result = new HashMap<>();
            result.put("projectId", newProjectId);
            result.put("createResponse", createResponse.getValues());
            result.put("updateResponse", updateResponse.getValues());
            result.put("historyCount", historyCount);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("创建测试历史记录失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("创建测试历史记录失败: " + e.getMessage());
        }
    }

    /**
     * List all projects using the getAllProjectIds contract method 
     * and then fetch complete details for each project
     */
    @GetMapping("/projects/blockchain")
    public ResponseEntity<?> getBlockchainProjects() {
        try {
            MedicalCrowdsourcingService service = getService();
            
            // 1. Get all project IDs from the blockchain - including deleted projects
            MedicalCrowdsourcingGetAllProjectIdsInputBO input = new MedicalCrowdsourcingGetAllProjectIdsInputBO();
            input.setIncludeDeleted(true); // 获取所有项目，包括已删除的项目
            CallResponse idsResponse = service.getAllProjectIds(input);
            log.info("Project IDs response: " + idsResponse.getValues());
            
            // Parse the list of project IDs
            List<Object> rawIds = parseListResponse(idsResponse.getValues());
            List<Map<String, Object>> projects = new ArrayList<>();
            
            // 2. For each ID, fetch complete project details
            for (Object rawId : rawIds) {
                try {
                    BigInteger projectId = new BigInteger(rawId.toString());
                    Map<String, Object> project = new HashMap<>();
                    project.put("id", projectId);
                    
                    // Get basic info 1 (id, title, description, dataHash)
                    MedicalCrowdsourcingGetProjectBasic1InputBO input1 = new MedicalCrowdsourcingGetProjectBasic1InputBO();
                    input1.set_projectId(projectId);
                    CallResponse basic1Response = service.getProjectBasic1(input1);
                    project.put("basic1", basic1Response.getValues());
                    
                    // Get basic info 2 (researcherInfo, completed, isDeleted)
                    MedicalCrowdsourcingGetProjectBasic2InputBO input2 = new MedicalCrowdsourcingGetProjectBasic2InputBO();
                    input2.set_projectId(projectId);
                    CallResponse basic2Response = service.getProjectBasic2(input2);
                    project.put("basic2", basic2Response.getValues());
                    
                    // Get project timestamps (creationTime, deletionTime, deletionReason)
                    MedicalCrowdsourcingGetProjectTimesInputBO timesInput = new MedicalCrowdsourcingGetProjectTimesInputBO();
                    timesInput.set_projectId(projectId);
                    CallResponse timesResponse = service.getProjectTimes(timesInput);
                    project.put("times", timesResponse.getValues());
                    
                    // Format response into a more usable structure
                    Map<String, Object> formattedProject = formatProjectData(project);
                    projects.add(formattedProject);
                    
                    log.info("Successfully fetched details for project ID " + projectId);
                } catch (Exception e) {
                    log.error("Error fetching details for project ID " + rawId, e);
                }
            }
            
            return ResponseEntity.ok(projects);
        } catch (Exception e) {
            log.error("Error fetching blockchain projects", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error fetching blockchain projects: " + e.getMessage());
        }
    }

    /**
     * Get transaction history for a specific project
     */
    @GetMapping("/projects/{projectId}/blockchain-transactions")
    public ResponseEntity<?> getBlockchainTransactions(@PathVariable String projectId) {
        try {
            MedicalCrowdsourcingService service = getService();
            BigInteger projectIdBigInt = new BigInteger(projectId);
            
            // Get transaction hashes for this project
            MedicalCrowdsourcingGetProjectTransactionsInputBO input = new MedicalCrowdsourcingGetProjectTransactionsInputBO();
            input.set_projectId(projectIdBigInt);
            CallResponse txResponse = service.getProjectTransactions(input);
            
            List<Object> txHashes = parseListResponse(txResponse.getValues());
            List<Map<String, Object>> transactions = new ArrayList<>();
            
            // For each transaction hash, get the details
            for (Object txHash : txHashes) {
                try {
                    MedicalCrowdsourcingGetTransactionDetailsInputBO detailsInput = new MedicalCrowdsourcingGetTransactionDetailsInputBO();
                    detailsInput.set_txHash(txHash.toString().getBytes());
                    CallResponse detailsResponse = service.getTransactionDetails(detailsInput);
                    
                    Map<String, Object> transaction = new HashMap<>();
                    transaction.put("hash", txHash.toString());
                    transaction.put("details", detailsResponse.getValues());
                    transactions.add(transaction);
                } catch (Exception e) {
                    log.error("Error fetching details for transaction " + txHash, e);
                }
            }
            
            return ResponseEntity.ok(transactions);
        } catch (Exception e) {
            log.error("Error fetching blockchain transactions", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error fetching blockchain transactions: " + e.getMessage());
        }
    }

    /**
     * Helper method to parse list responses from the blockchain
     */
    private List<Object> parseListResponse(Object response) {
        List<Object> result = new ArrayList<>();
        
        if (response instanceof List) {
            return (List<Object>) response;
        } else if (response instanceof String) {
            String responseStr = (String) response;
            // Remove brackets and split by comma
            String[] parts = responseStr.replaceAll("[\\[\\]\"]", "").split(",");
            for (String part : parts) {
                if (!part.trim().isEmpty()) {
                    result.add(part.trim());
                }
            }
        }
        
        return result;
    }

    /**
     * Format project data into a more usable structure
     */
    private Map<String, Object> formatProjectData(Map<String, Object> rawProject) {
        Map<String, Object> formatted = new HashMap<>();
        formatted.put("id", rawProject.get("id"));
        
        // Parse basic1 data (id, title, description, dataHash)
        List<Object> basic1Data = parseListResponse(rawProject.get("basic1"));
        if (basic1Data.size() >= 4) {
            formatted.put("id", basic1Data.get(0)); // id
            formatted.put("title", basic1Data.get(1)); // title
            formatted.put("description", basic1Data.get(2)); // description
            formatted.put("hash", basic1Data.get(3)); // dataHash
        }
        
        // Parse basic2 data (researcherInfo, completed, isDeleted)
        List<Object> basic2Data = parseListResponse(rawProject.get("basic2"));
        if (basic2Data.size() >= 3) {
            formatted.put("researcherInfo", basic2Data.get(0)); // researcherInfo
            formatted.put("isCompleted", "true".equals(basic2Data.get(1).toString())); // completed
            formatted.put("isDeleted", "true".equals(basic2Data.get(2).toString())); // isDeleted
            
            // 根据isDeleted和isCompleted确定状态码
            int statusCode = 0; // Default: ACTIVE
            if ("true".equals(basic2Data.get(2).toString())) {
                statusCode = 3; // DELETED
            } else if ("true".equals(basic2Data.get(1).toString())) {
                statusCode = 2; // COMPLETED
            }
            formatted.put("status", statusCode);
        }
        
        // Parse times data (creationTime, deletionTime, deletionReason)
        List<Object> timesData = parseListResponse(rawProject.get("times"));
        if (timesData.size() >= 3) {
            formatted.put("createdAt", timesData.get(0)); // creationTime
            formatted.put("deletedAt", timesData.get(1)); // deletionTime
            formatted.put("deletionReason", timesData.get(2)); // deletionReason
        }
        
        return formatted;
    }

    /**
     * 获取所有项目列表，包括已删除的项目，并以列表形式返回简要信息
     */
    @GetMapping("/projects/all")
    public ResponseEntity<?> getAllProjects() {
        try {
            MedicalCrowdsourcingService service = getService();
            
            // 获取所有项目ID，包括已删除的
            MedicalCrowdsourcingGetAllProjectIdsInputBO input = new MedicalCrowdsourcingGetAllProjectIdsInputBO();
            input.setIncludeDeleted(true);
            CallResponse idsResponse = service.getAllProjectIds(input);
            
            List<Object> rawIds = parseListResponse(idsResponse.getValues());
            List<Map<String, Object>> projectsList = new ArrayList<>();
            
            // 为每个项目ID获取基本信息
            for (Object rawId : rawIds) {
                try {
                    BigInteger projectId = new BigInteger(rawId.toString());
                    Map<String, Object> project = new HashMap<>();
                    
                    // 获取基本信息1（标题、描述等）
                    MedicalCrowdsourcingGetProjectBasic1InputBO input1 = new MedicalCrowdsourcingGetProjectBasic1InputBO();
                    input1.set_projectId(projectId);
                    CallResponse basic1Response = service.getProjectBasic1(input1);
                    
                    // 获取基本信息2（研究者、状态等）
                    MedicalCrowdsourcingGetProjectBasic2InputBO input2 = new MedicalCrowdsourcingGetProjectBasic2InputBO();
                    input2.set_projectId(projectId);
                    CallResponse basic2Response = service.getProjectBasic2(input2);
                    
                    // 获取时间信息
                    MedicalCrowdsourcingGetProjectTimesInputBO timesInput = new MedicalCrowdsourcingGetProjectTimesInputBO();
                    timesInput.set_projectId(projectId);
                    CallResponse timesResponse = service.getProjectTimes(timesInput);
                    
                    // 解析并组装简要信息
                    List<Object> basic1Data = parseListResponse(basic1Response.getValues());
                    List<Object> basic2Data = parseListResponse(basic2Response.getValues());
                    List<Object> timesData = parseListResponse(timesResponse.getValues());
                    
                    if (basic1Data.size() >= 4 && basic2Data.size() >= 3) {
                        project.put("id", projectId);
                        project.put("title", basic1Data.get(1));
                        project.put("description", basic1Data.get(2));
                        project.put("researcherInfo", basic2Data.get(0));
                        project.put("isCompleted", "true".equals(basic2Data.get(1).toString()));
                        project.put("isDeleted", "true".equals(basic2Data.get(2).toString()));
                        
                        if (timesData.size() >= 3) {
                            project.put("createdAt", timesData.get(0));
                            project.put("deletedAt", timesData.get(1));
                            project.put("deletionReason", timesData.get(2));
                        }
                        
                        // 根据状态确定状态码
                        int statusCode = 0; // 默认：活跃
                        if ("true".equals(basic2Data.get(2).toString())) {
                            statusCode = 3; // 已删除
                        } else if ("true".equals(basic2Data.get(1).toString())) {
                            statusCode = 2; // 已完成
                        }
                        project.put("status", statusCode);
                        
                        projectsList.add(project);
                    }
                } catch (Exception e) {
                    log.error("获取项目ID " + rawId + " 的详情失败", e);
                }
            }
            
            return ResponseEntity.ok(projectsList);
        } catch (Exception e) {
            log.error("获取所有项目列表失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("获取所有项目列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取未删除的项目列表，只返回未被删除的项目
     */
    @GetMapping("/projects/active")
    public ResponseEntity<?> getActiveProjects() {
        try {
            MedicalCrowdsourcingService service = getService();
            
            // 获取未删除的项目ID
            MedicalCrowdsourcingGetAllProjectIdsInputBO input = new MedicalCrowdsourcingGetAllProjectIdsInputBO();
            input.setIncludeDeleted(false); // 仅获取未删除的项目
            CallResponse idsResponse = service.getAllProjectIds(input);
            
            List<Object> rawIds = parseListResponse(idsResponse.getValues());
            List<Map<String, Object>> activeProjects = new ArrayList<>();
            
            // 为每个项目ID获取详细信息
            for (Object rawId : rawIds) {
                try {
                    BigInteger projectId = new BigInteger(rawId.toString());
                    Map<String, Object> project = new HashMap<>();
                    
                    // 获取基本信息1
                    MedicalCrowdsourcingGetProjectBasic1InputBO input1 = new MedicalCrowdsourcingGetProjectBasic1InputBO();
                    input1.set_projectId(projectId);
                    CallResponse basic1Response = service.getProjectBasic1(input1);
                    
                    // 获取基本信息2
                    MedicalCrowdsourcingGetProjectBasic2InputBO input2 = new MedicalCrowdsourcingGetProjectBasic2InputBO();
                    input2.set_projectId(projectId);
                    CallResponse basic2Response = service.getProjectBasic2(input2);
                    
                    // 获取时间信息
                    MedicalCrowdsourcingGetProjectTimesInputBO timesInput = new MedicalCrowdsourcingGetProjectTimesInputBO();
                    timesInput.set_projectId(projectId);
                    CallResponse timesResponse = service.getProjectTimes(timesInput);
                    
                    // 解析并组装项目信息
                    List<Object> basic1Data = parseListResponse(basic1Response.getValues());
                    List<Object> basic2Data = parseListResponse(basic2Response.getValues());
                    List<Object> timesData = parseListResponse(timesResponse.getValues());
                    
                    if (basic1Data.size() >= 4 && basic2Data.size() >= 3) {
                        // 额外检查确认项目未被删除
                        boolean isDeleted = "true".equals(basic2Data.get(2).toString());
                        if (!isDeleted) {
                            project.put("id", projectId);
                            project.put("title", basic1Data.get(1));
                            project.put("description", basic1Data.get(2));
                            project.put("researcherInfo", basic2Data.get(0));
                            project.put("isCompleted", "true".equals(basic2Data.get(1).toString()));
                            project.put("createdAt", timesData.size() >= 1 ? timesData.get(0) : null);
                            
                            // 根据完成状态确定状态码
                            int statusCode = "true".equals(basic2Data.get(1).toString()) ? 2 : 0; // 2=已完成, 0=活跃
                            project.put("status", statusCode);
                            
                            activeProjects.add(project);
                        }
                    }
                } catch (Exception e) {
                    log.error("获取项目ID " + rawId + " 的详情失败", e);
                }
            }
            
            return ResponseEntity.ok(activeProjects);
        } catch (Exception e) {
            log.error("获取活跃项目列表失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("获取活跃项目列表失败: " + e.getMessage());
        }
    }
} 